package com.ist.viewpagerhelper.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Scroller;

import com.ist.viewpagerhelper.GlideManager;
import com.ist.viewpagerhelper.R;
import com.ist.viewpagerhelper.bean.ViewPagerBean;
import com.ist.viewpagerhelper.indicator.NormalIndicator;
import com.ist.viewpagerhelper.indicator.TransIndicator;
import com.ist.viewpagerhelper.indicator.ZoomIndicator;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by zhengshaorui on 2017/10/29.
 * csdn: http://blog.csdn.net/u011418943
 */

public class BannerViewPager extends ViewPager implements View.OnTouchListener {
    
    /**
     * const
     */
    private static final String TAG = "LoopViewPager";
    private static final int LOOP_MSG = 0x1001;
    private static final int LOOP_COUNT = 5000;
    /**
     * logic
     */
    private int mLoopTime;
    private int mCurrentIndex;
    private boolean isFirst = true;
    private List<View> mViews;
    private boolean isLoop;
    private Context mContext;
    private int mSwitchTime;
    /**
     * handle
     */
    private Handler mHandler = new Handler(Looper.getMainLooper()){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == LOOP_MSG){
                mCurrentIndex = getCurrentItem(); //重新获取index
                if (mCurrentIndex >= LOOP_COUNT/2){
                    mCurrentIndex ++;
                }
                if (mCurrentIndex > LOOP_COUNT){
                    mCurrentIndex = LOOP_COUNT/2;
                }
                setCurrentItem(mCurrentIndex);
                mHandler.sendEmptyMessageDelayed(LOOP_MSG,mLoopTime);
            }
        }
    };

    public BannerViewPager(Context context) {
        this(context,null);
    }

    public BannerViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.BannerViewPager);
        isLoop = ta.getBoolean(R.styleable.BannerViewPager_isloop,false);
        mLoopTime = ta.getInteger(R.styleable.BannerViewPager_looptime,1000);
        mSwitchTime = ta.getInteger(R.styleable.BannerViewPager_switchtime,800);
        ta.recycle();
    }


    public void setViewPagerBean(ViewPagerBean bean){

        setBannerDatas(bean.objects);
        if (bean.bottomLayout != null) {
            if (bean.bottomLayout instanceof ZoomIndicator) {
                ZoomIndicator zoomIndicator = (ZoomIndicator) bean.bottomLayout;
                zoomIndicator.setLoopData(bean);
            }
            if (bean.bottomLayout instanceof NormalIndicator){
                NormalIndicator normalIndicator = (NormalIndicator) bean.bottomLayout;
                normalIndicator.setViewPagerData(bean);
            }

            if (bean.bottomLayout instanceof TransIndicator){
                TransIndicator transIndicator = (TransIndicator) bean.bottomLayout;
                transIndicator.setViewPagerData(bean);
            }

        }

    }

    /**
     * 用来加载图片的类型
     * @param datas
     */
    private void setBannerDatas(Object[] datas) {
        if (datas != null){
            mViews = new ArrayList<>();
            for (int i = 0; i < datas.length; i++) {
                ImageView imageView = new ImageView(mContext);
                imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                Object object = datas[i];

                if (object instanceof String){
                   new GlideManager.Builder()
                           .setContext(mContext)
                           .setTargetSource((String) object)
                           .setLoadingBitmap(R.mipmap.ic_launcher)
                           .setImageView(imageView)
                           .builder();
                }
                if (object instanceof Integer){
                    new GlideManager.Builder()
                            .setContext(mContext)
                            .setTargetSource((Integer) object)
                            .setLoadingBitmap(R.mipmap.ic_launcher)
                            .setImageView(imageView)
                            .builder();
                }
                mViews.add(imageView);
            }
            setAdapter(new CusTomAdapter(mViews));
            setCurrentItem(LOOP_COUNT/2+mViews.size());
            setOnTouchListener(this);
            initSwitchTime();
            if (isLoop){
                mHandler.sendEmptyMessageDelayed(LOOP_MSG,mLoopTime);
            }
        }
    }

    /**
     * 设置viewpager 之间的切换速度
     */
    private void initSwitchTime(){
        try {
            Field field = ViewPager.class.getDeclaredField("mScroller");
            field.setAccessible(true);
            field.set(this,bannerScroller);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void onPause(){
        if (isFocused()) {
            mHandler.removeMessages(LOOP_MSG);
        }
    }
    public void onReusme(){
        if (isLoop) {
            if (!isFirst) {
                mHandler.removeMessages(LOOP_MSG);
                mHandler.sendEmptyMessageDelayed(LOOP_MSG, mLoopTime);
            }
        }
    }

    /**
     * 修改 切换速度
     */
    private Scroller bannerScroller = new Scroller(getContext()){
        @Override
        public void startScroll(int startX, int startY, int dx, int dy, int duration) {
            super.startScroll(startX, startY, dx, dy, mSwitchTime);
        }

        @Override
        public void startScroll(int startX, int startY, int dx, int dy) {
            super.startScroll(startX, startY, dx, dy,mSwitchTime);
        }
    };

    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        mHandler.removeMessages(LOOP_MSG);
        switch (motionEvent.getAction()){
            case MotionEvent.ACTION_UP :
                mHandler.sendEmptyMessageDelayed(LOOP_MSG,mLoopTime);
                break;

            default:
                break;
        }
        return false;
    }


    /**
     * viewpager 的 adapter
     */
    class CusTomAdapter extends PagerAdapter{

        List<View> views ;

        public CusTomAdapter(List<View> views) {
            this.views = views;
        }

        @Override
        public int getCount() {
            return LOOP_COUNT + this.views.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            View view = null;
            if (this.views != null){
                //对Viewpager页号求模去除View列表中要显示的项
                position %= this.views.size();

                //如果View已经在之前添加到了一个父组件，则必须先remove，否则会抛出IllegalStateException。
                view = this.views.get(position);
                ViewGroup viewParent = (ViewGroup) view.getParent();

                if (viewParent!=null){
                    //viewParent.removeView(view);
                }
                container.addView(view);
            }
            return view;

        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);

        }
    }


}
